<?

define('CHECK_EXTERNAL_USER','SELECT * FROM `external_users` WHERE `login` = ? AND `password` = ?');
define('ADD_EXTERNAL_SESSION','INSERT INTO `external_sessions` (`session_id` ,`ip` ,`user_id` ,`date`) VALUES (?, ?, ?, now())');

define('DELETE_EXTERNAL_SESSION','DELETE FROM `external_sessions` WHERE `session_id` = ?');

define('CHECK_EXTERNAL_SESSION','SELECT * FROM `external_sessions` WHERE session_id = ?');

define ('GET_EXTERNAL_USER','SELECT * FROM `external_users` WHERE `login` = ? ');
define ('GET_EXTERNAL_USER_BY_EMAIL','SELECT * FROM `external_users` WHERE `email` = ? ');
define ('GET_EXTERNAL_USER_BY_CODE','SELECT * FROM `external_users` WHERE `confirmation_id` = ? ');
define ('GET_EXTERNAL_USER_BY_ID','SELECT * FROM `external_users` WHERE `id` = ? ');

define ('SET_NEW_PASSWORD','UPDATE `external_users` SET `password` = ? WHERE `id` =? ');

define ('UPDATE_NEW_USER','UPDATE `external_users` SET `realname` = ?, `email` = ? WHERE `id` = ?');
define ('CHANGE_NEW_USER_PASSWORD','UPDATE `external_users` SET `password` = ? WHERE `id` = ?');

class Model_Externaluser extends Models_Base {
	
	function createSession($username, $password) {

		if(empty($username) && empty($password))
			return false;


		$sth = $this->dbh->prepare(CHECK_EXTERNAL_USER);
		
		$sth->execute(array($username, md5(md5($password))));
		$result = $sth->fetch();

		if(isset($result)) {
		
			if (!$result[id])
				throw new UserException ("Такой пары логин-пароль не существует!");

			if (!$result[confirmed])
				throw new UserException ("Email не подтвержден!");

			if (!$result[enabled])
				throw new UserException ("Пользователь заблокирован!");
			
		
			$sth = $this->dbh->prepare(ADD_EXTERNAL_SESSION);
			
			$SID = $this->generateRandomString(20);
			
			$result = $sth->execute(
				array(
					$SID,
					$_SERVER['REMOTE_ADDR'],
					$result[id],
				)
			);
			
			return $result ? $SID : false;
		} 
		
	}
	
	
	private function generateRandomString($num = 20) {
		
		$sesid = '';
		$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		
		while(strlen($sesid) < $num) {

			$sesid .= $string[rand(0,62)];
		} 

		return $sesid;
	}
	
	function checkSession($SID) {
		// TODO make more intellegent CHECK_EXTERNAL_SESSION
		$sth = $this->dbh->prepare(CHECK_EXTERNAL_SESSION);
		$sth->execute(array($SID));
		
		$session = $sth->fetchObject();
		
		return $this->getUserByID($session->user_id);
	}

	function getUserByID($id) {
		$sth = $this->dbh->prepare(GET_EXTERNAL_USER_BY_ID);
		$sth->execute(array($id));
		
		return $sth->fetchObject();
	}


	function getUser($username) {
		$sth = $this->dbh->prepare(GET_EXTERNAL_USER);
		$sth->execute(array($username));
		
		return $sth->fetch();
	}
	
	function getUserByEmail($email) {
		$sth = $this->dbh->prepare(GET_EXTERNAL_USER_BY_EMAIL);
		$sth->execute(array($email));
		
		return $sth->fetch();
		
	}

	function getUserByCode($code) {
		$sth = $this->dbh->prepare(GET_EXTERNAL_USER_BY_CODE);
		$sth->execute(array($code));
		
		return $sth->fetchObject();
		
	}

	function deleteSession($SID) {
		$sth = $this->dbh->prepare(DELETE_EXTERNAL_SESSION);
		return $sth->execute(array($SID)); 
				
	}

	function checkEmail($email){
		return preg_match("/[a-zA-Z0-9\.\-\_]+\@[a-zA-Z0-9\.\-\_]+\.[a-zA-Z0-9\.\-\_]{2,3}/", $email) 
			? true
			: false;
	}
	
	function generateNewPassword($username,$email) {

		
		if(!$this->checkEmail($email))
			throw new UserException ("Некорректный email!");		
		
		$user = $this->getUserByEmail($email);


		if($user[login] != $username )
			throw new UserException ("Нет такой пары имя пользователя - email");

		if(empty($user))
			throw new UserException ("Такого адреса нет в БД!");

			
		$password = $this->generateRandomString(10);

		$sth = $this->dbh->prepare(SET_NEW_PASSWORD);
		$result = $sth->execute(array(md5(md5($password)),$user[id]));

		$mail = new Model_Mail($this->register);
		$mail->send($email,'Восстановление забытого пароля',"Новый пароль: $password");

		return $result ? true : false;
		
	}

	function updateUser($name, $email, $id) {
		
		if(empty($name))
			throw new UserException ("Имя не может быть пустым!");
		
		if(empty($email))
			throw new UserException ("Email не может быть пустым!");
			
		if (!filter_var($email, FILTER_VALIDATE_EMAIL))
			throw new UserException ("Некорректный email");
			
		$sth = $this->dbh->prepare(UPDATE_NEW_USER);
		return $sth->execute(array($name, $email, $id));
		
	}
	
	function changePassword ($password, $password2, $id) {
		
		if(empty( $password ))
			throw new UserException ("Введите пароль");

		if(!empty( $password ) && (strlen( $password ) < 3 || strlen( $password ) > 20 ))
			throw new UserException ("Длина пароля должна быть от 3 до 20 символов");

		if( $password != $password2 )
			throw new UserException ("Пароли не совпадают");
		
		$sth = $this->dbh->prepare(CHANGE_NEW_USER_PASSWORD);
		return $sth->execute(array(md5(md5($password)), $id));			
		
	}	
	
}

?>